package ar.com.globallogic.promomr.services;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import ar.com.globallogic.promomr.domain.Content;
import ar.com.globallogic.promomr.exceptions.FileUploadException;

@Service
public class FileServiceImpl implements FileService {

	private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
	
	@Value("${upload.dir}")
	private String uploadDir;

	public void save(String fileName, MultipartFile file) {
		logger.info(String.format("Saving file with name %s.", fileName));
		if (!file.isEmpty()) {
			Path path = Paths.get(uploadDir, fileName);
			try {
				Files.write(path, file.getBytes(), StandardOpenOption.CREATE);
			} catch (IOException e) {
				logger.error(String.format("File with name %s was not saved.", fileName));
				logger.debug("StackTrace: " + e.getStackTrace());
				throw new FileUploadException(fileName);
			}
		}else{
			logger.error(String.format("File with name %s was not saved.", fileName));
			throw new FileUploadException(fileName);
		}
		logger.info(String.format("File with name %s was saved.", fileName));
	}
	
	@Override
	public String getFileNameForContent(MultipartFile file, Content content) {
		return content.getId() + "." + getFileExtension(file);
	}
	
	private String getFileExtension(MultipartFile file){
		String filename = file.getOriginalFilename();
		return filename.substring(filename.lastIndexOf( "." ) + 1 );
	}

	public void setUploadDir(String uploadDir) {
		this.uploadDir = uploadDir;
	}
}
